package com.example.administrator.futurehope;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.SyncStateContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.protocol.AsyncThread;
import com.protocol.HttpAsync;
import com.protocol.URLConfig;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.CookieStore;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.client.protocol.ClientContext;
import cz.msebera.android.httpclient.cookie.Cookie;
import cz.msebera.android.httpclient.impl.client.AbstractHttpClient;
import cz.msebera.android.httpclient.impl.client.BasicCookieStore;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.protocol.BasicHttpContext;
import cz.msebera.android.httpclient.protocol.HttpContext;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class OaActivity extends BaseActivity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_oa);
        findView();
        init();
        SetListner();
    }

    public void findView() {
        webView = (WebView) findViewById(R.id.webView);

    }

    public void init() {

//        Intent intent = new Intent();
//        intent.setAction("android.intent.action.VIEW");
//        Uri content_url = Uri.parse(URLConfig.OAINDEX);
//        intent.setData(content_url);
//        startActivity(intent);


//        getCookie();
//        getdate();
        loadURL();
        //启用支持javascript
//        WebSettings settings = webView.getSettings();
//        settings.setJavaScriptEnabled(true);
////        webView.loadUrl(URLConfig.OAINDEX);
//        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
//        webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                // TODO Auto-generated method stub
//                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
//                view.loadUrl(url);
//                return true;
//            }
//        });


    }

    @Override
    public void SetListner() {

    }


//    public void getCookie() {
//        String url = "http://116.55.242.231:8084/officemanager/member/login/jackson&111111";
//        String urlindex = "http://116.55.242.231:8084/officemanagerView/view/page/index.html?name=jackson&p=111111";
//        // //获取webview里面的cookie信息
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.setAcceptCookie(true);
//        String cookieStr = cookieManager.getCookie(url);
////        CookieBean cookieBean = new CookieBean(cookieStr, PostEventAction.COOKIE_DOMAIN_HOST);
////        HttpCookieManager.saveCookie(getApplicationContext(), cookieBean, 0);
////        Logger.e("sunzn", "Cookies = " + cookieStr);
//
//
//        CookieSyncManager.createInstance(OaActivity.this);
//        CookieManager cookieManager2 = CookieManager.getInstance();
//        cookieManager2.setAcceptCookie(true);
//        cookieManager2.setCookie(urlindex, cookieStr);//cookies是在HttpClient中获得的cookie
//        CookieSyncManager.getInstance().sync();
//        webView.loadUrl(urlindex);
//    }

//    private void syncCookie(Context context, String url) {
//        try {
//
//
//            CookieSyncManager.createInstance(context);
//
//            CookieManager cookieManager = CookieManager.getInstance();
//            cookieManager.setAcceptCookie(true);
//            //cookieManager.removeSessionCookie();// 移除
//            //cookieManager.removeAllCookie();//清除所有cookie
//
//            //log
//            String oldCookie = cookieManager.getCookie(url);
//            if (oldCookie != null) {
////                Log.d("Nat: webView.syncCookieOutter.oldCookie", oldCookie);
//            }
//
//            //参数 - 通过Builder形式
//            StringBuilder sbCookie = new StringBuilder();
//            sbCookie.append(String.format("JSESSIONID=%s", "5AC6268DD8D4D5D1FDF5D41E9F2FD961"));
//            sbCookie.append(String.format(";domain=%s", URLConfig.OALOGIN));
//            sbCookie.append(String.format(";path=%s", "8084"));
//            String cookieValue = sbCookie.toString();
//            cookieManager.setCookie(url, cookieValue);
//
////            //参数 - 单独形式
////            cookieManager.setCookie(url, "JSESSIONID=" + sid);
////            cookieManager.setCookie(url, "access_token=" + stoken);
//
//            //最后一定要调用
//            CookieSyncManager.getInstance().sync();
//
//            //log
//            String newCookie = cookieManager.getCookie(url);
//            if (newCookie != null) {
////                Log.d("Nat: webView.syncCookie.newCookie", newCookie);
//            }
//        } catch (Exception e) {
////            Log.e("Nat: webView.syncCookie failed", e.toString());
//        }
//    }


    public void getdate() {
        String ENTRANCE_URL_LOGIN = URLConfig.OALOGIN; //登陆url

        final String ENTRANCE_URL_HOME = URLConfig.OAINDEX; //登陆后调整的url
        CookieManager cookieManager = CookieManager.getInstance();
        String CookieStr = cookieManager.getCookie(ENTRANCE_URL_HOME); //获取cookie

//        SharedPreferences sharedPreferences= getSharedPreferences("test",
//                Activity.MODE_PRIVATE);
//        //实例化SharedPreferences.Editor对象
//        SharedPreferences.Editor editor = sharedPreferences.edit();
//        //用putString的方法保存数据
//        editor.putString("membername","jackson");
//        editor.putString("psw","psw");
//
//        //提交当前数据
//        editor.apply();

        CookieSyncManager.createInstance(OaActivity.this);
        cookieManager.setAcceptCookie(true);
//        cookieManager.setCookie(URLConfig.OAINDEX, cookieValue);//cookies是在HttpClient中获得的cookie
        cookieManager.setCookie(URLConfig.OAINDEX, CookieStr);
        CookieSyncManager.getInstance().sync();
        loadURL();
//        HttpAsync.gethttp(URLConfig.OALOGIN).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                String htmlStr = response.body().string();
////                Log.e("lz", "htmlStr:" + htmlStr);
//                Message message = new Message();
//                message.obj = htmlStr;
//                message.what = URLConfig.SUCCESS;
//                handler.sendMessage(message);
//            }
//        });

//            String CookieStr = HttpAsync.getCookie(new URL(URLConfig.OALOGIN));

//        try {
//
//
//            AsyncThread thead = new AsyncThread(getApplicationContext()) {
//
//                @Override
//                public Object executeRun(Object... params) {
//
//                    HttpClient client = new DefaultHttpClient();
//                    try {
////                        HttpAsync.getCookie(URLConfig.OALOGIN);
//                        HttpGet get = new HttpGet(URLConfig.OAINDEX);//登陆后跳转页面的地址
////                        post.setEntity(new UrlEncodedFormEntity(list));
//                        HttpContext context = new BasicHttpContext();
//                        CookieStore cookieStore = new BasicCookieStore();
//                        context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
//                        HttpResponse response = client.execute(get);
//                        if (response.getStatusLine().getStatusCode() == 200) {
//                            AbstractHttpClient absClent = (AbstractHttpClient) client;
//                            List<Cookie> cookies = absClent.getCookieStore().getCookies();
//
//                            for (Cookie cookie : cookies) {
//                                //打印信息与上面传入信息相同
////                                Log.e(">>>>>>>>>>>>>>>>>>>", "name=" + cookie.getName() + "password=" + cookie.getValue());
////                                Message message = new Message();
////                                message.obj = cookie;
////                                handler.sendMessage(message);
//                                return cookie;
//                            }
//                        }
//                    } catch (Exception e) {
//                        // TODO Auto-generated catch block
//                        e.printStackTrace();
//                    }
//
//                    return "";
//                }
//
//                @Override
//                public void executeBefore() {
//                    // TODO Auto-generated method stub
//
//                }
//
//                @Override
//                public void executeAfter(Object obj) {
//                    showToast(obj.toString());
//                }
//            };
//            thead.start();
//
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }


    }
//
//    Handler handler = new Handler() {
//        public void handleMessage(Message msg) {
//            Object o = msg.obj;
//            switch (msg.what) {
//                case URLConfig.FAIL:
//                    showToast(o.toString());
//                    break;
//                case URLConfig.SUCCESS:
////                    showToast(o.toString());
//                    setcookie(o.toString());
//            }
//            super.handleMessage(msg);
//        }
//    };
//
//
//    public void setcookie(String obj) {
//
//        StringBuilder sbCookie = new StringBuilder();
////        sbCookie.append(String.format("JSESSIONID=%s", "INPUT YOUR JSESSIONID STRING"));
////        sbCookie.append(String.format(";domain=%s", "INPUT YOUR DOMAIN STRING"));
////        sbCookie.append(String.format(";path=%s", "INPUT YOUR PATH STRING"));
//
//        try {
//            JSONObject object = new JSONObject(obj);
//            String values = object.getString("values");
//            JSONArray array = new JSONArray(values);
//            JSONObject item = array.getJSONObject(0);
//            String member_email = item.getString("member_email");
//            String member_id = item.getString("member_id");
//            String member_name = item.getString("member_name");
//            String nickname = item.getString("nickname");
//            String organization_id = item.getString("organization_id");
//            String member_email_psw = item.getString("member_email_psw");
//            String member_code = item.getString("member_code");
//            String organization_name = item.getString("organization_name");
////            String organization_code = item.getString("organization_code");
//            sbCookie.append(String.format("member_email", member_email));
//            sbCookie.append(String.format("member_id", member_id));
//            sbCookie.append(String.format("member_name", member_name));
//            sbCookie.append(String.format("nickname", nickname));
//            sbCookie.append(String.format("organization_id", organization_id));
//            sbCookie.append(String.format("member_email_psw", member_email_psw));
//            sbCookie.append(String.format("member_code", member_code));
////            sbCookie.append(String.format("organization_code", organization_code));
//            sbCookie.append(String.format("organization_name", organization_name));
//            sbCookie.append(String.format(";path=%s", URLConfig.OAINDEX));
//            String cookieValue = sbCookie.toString();
//            CookieSyncManager.createInstance(OaActivity.this);
//            CookieManager cookieManager = CookieManager.getInstance();
//            cookieManager.setAcceptCookie(true);
////        cookieManager.setCookie(URLConfig.OAINDEX, cookieValue);//cookies是在HttpClient中获得的cookie
//            cookieManager.setCookie(URLConfig.OAINDEX, cookieValue);
//            CookieSyncManager.getInstance().sync();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//
//        loadURL();
//    }

    public void loadURL() {

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
            }

            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
            }
        });
        webView.loadUrl(URLConfig.OALOGIN_VIEW);
    }


    //改写物理按键——返回的逻辑
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();//返回上一页面
                return true;
            } else {
                System.exit(0);//退出程序
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
